package org.amq.client.sender;

import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.amq.base.util.ApplicationContextHolder;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.jms.pool.PooledConnectionFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;

@Component
public class MessageSender {
    ExecutorService service = Executors.newSingleThreadExecutor();
    String connectionBeanName = "";

    public boolean sendToQueue(String queueName, final String json, final Map<String, String> prop) {
        JmsTemplate jmsTemplate = getJmsTemplate(connectionBeanName, queueName);
        jmsTemplate.send(new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                Message message = session.createTextMessage(json);
                for (Entry<String, String> entry : prop.entrySet()) {
                    message.setStringProperty(entry.getKey(), entry.getValue());
                }
                return message;
            }
        });
        return true;
    }

    public boolean sendToQueueThread(Set<String> sites, String bean, final String json,
            final Map<String, String> prop) {
        JmsSendThread thread = new JmsSendThread(sites, bean, json, prop);
        service.execute(thread);
        return true;
    }
    public static class JmsSendThread extends Thread {
        private final Map<String, String> prop;
        private final String bean;
        private final String json;
        private final Set<String> sites;

        public JmsSendThread(Set<String> sites, String bean, final String json, final Map<String, String> prop) {
            this.prop = prop;
            this.bean = bean;
            this.json = json;
            this.sites = sites;
        }

        @Override
        public void run() {
            // for (String toSite : sites) {
            // boolean sendSuccessFlag = false;
            // for (int i = 0; i < 6; i++) {
            // if (sendSuccessFlag) {
            // break;
            // }
            // try {
            // String queueName = SiteUtil.getQueueByFromAndTo(bean, SiteUtil.getCurSite(), toSite);
            // // 跟wms交互的时候不需要后缀
            // if (SiteUtil.WMS.equals(toSite)) {
            // queueName = bean;
            // }
            // sendSuccessFlag = FocusContainerTool.getApplicationContext()
            // .getBean(ActiveMqMessageSender.class).sendToQueue(queueName, json, prop);
            // }
            // catch (Exception e) {
            // logger.warn("JmsSendThread 次数：" + i, e);
            // }
            // }
            // if (!sendSuccessFlag) {
            //
            // }
            // }
        }
    }

    private PooledConnectionFactory getFactoryBySite(String connectionBean) {
        try {
            PooledConnectionFactory pooledConnectionFactory =
                    (PooledConnectionFactory) ApplicationContextHolder.getApplicationContext().getBean(connectionBean);
            return pooledConnectionFactory;
        }
        catch (Exception e) {
            throw new RuntimeException("can't find spring  bean PooledConnectionFactory name:" + connectionBean);
        }
    }

    private final Map<String, JmsTemplate> jmsMap = new ConcurrentHashMap<String, JmsTemplate>();

    private JmsTemplate getJmsTemplate(final String connectionBean, final String queueName) {
        StringBuffer jmsTemplateKey = new StringBuffer();
        jmsTemplateKey.append(connectionBean);
        jmsTemplateKey.append(queueName);
        if (!jmsMap.containsKey(jmsTemplateKey.toString())) {
            JmsTemplate jmsTemplate = new JmsTemplate(getFactoryBySite(connectionBean));
            ActiveMQQueue destination = new ActiveMQQueue(queueName);
            jmsTemplate.setDefaultDestination(destination);
            jmsTemplate.setSessionTransacted(true);
            jmsMap.put(jmsTemplateKey.toString(), jmsTemplate);
        }
        return jmsMap.get(jmsTemplateKey.toString());
    }
}
